﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;

namespace HelloWPF.Command.Command
{
    /// <summary>
    /// 继承ICommand，实现CanExecute，Execute
    /// </summary>
    public class CommandBase : ICommand
    {
        //public event EventHandler CanExecuteChanged;

        /// <summary>
        /// 我理解把CanExecute()方法挂载到CommandManager.RequerySuggested上面了
        /// </summary>
        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        /// <summary>
        /// 委托用来接收要执行的动作
        /// </summary>
        public Action<object> DoExecute { get; set; }

        /// <summary>
        /// 委托用来接收方法，而方法里面的逻辑返回true/false，决定控件是否可用
        /// </summary>
        public Func<object, bool> DoCanExecute { get; set; }

        /// <summary>
        /// 执行的具体动作
        /// </summary>
        public void Execute(object parameter)
        {
            //委托不为null了，则执行委托
            DoExecute?.Invoke(parameter);
        }

        /// <summary>
        /// 控件是否可用
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public bool CanExecute(object parameter)
        {
            Console.WriteLine($"CanExecute ThreadId:{Thread.CurrentThread.ManagedThreadId.ToString("00")}");
            //委托不为null了，则执行委托
            return DoCanExecute?.Invoke(parameter) == true;
        }

        /// <summary>
        /// ViewModel不能直接调用事件，所以包一层，类内部调用事件
        /// </summary>
        public void RaiseCanExecuteChanged()
        {
            //CanExecuteChanged?.Invoke(this, new EventArgs());
        }
    }
}
